<?php

namespace app\uapi\controller;

use app\admin\model\KnscyRedpack;
use app\admin\model\KnscyRedpackAgent;
use app\common\controller\ApiController;
use app\common\service\GoodService;
use app\common\service\OrderService;
use think\facade\Db;

class Coupon extends ApiController
{
    public static $needLoginAction = [
        'agentCoupon', //用户申领优惠券
        'myCouponList', //我的优惠券列表
        'myCouponDetail', //我的优惠券详情 线下凭证去扫码页面
    ];

    /**
     * 获取可用的券
     * @return void
     */
    public function couponList()
    {
        $limit = $this->request->post('limit', 10);
        $page = $this->request->post('page', 1);
        $type = $this->request->post('type', 0);
        //用户判断是否领取过
        $my_agent = KnscyRedpackAgent::where('user_id', $this->user_id)->column('redpack_no');

        $List = KnscyRedpack::where('status', 1)
            ->whereTime('start_time', '<=', date('Y-m-d H:i:s'))
            ->whereTime('end_time', '>=', date('Y-m-d H:i:s'))
            ->order(Db::raw('sort=0,sort asc,id desc'))
            ->paginate(
                [
                    'list_rows' => $limit,
                    'page' => $page,
                ]
            )->each(function ($item) use ($my_agent, $type) {
                $item['can_get'] = 1;
                $item['type_label'] = $item->type_label;
                if( $my_agent && in_array($item->redpack_no, $my_agent) ) {
                    $item['can_get'] = 0;
                }
            });
        if ($type == 0)
            $this->success('success', $List);
        else
            $this->success('success', []);
    }

    public function agentCoupon()
    {
        $redPack_no = $this->request->post('redpack_no');

        $info = KnscyRedpack::where('redpack_no', $redPack_no)->find();
        if (empty($info)) {
            $this->error('券信息有误',[],1);
        }
        //检查是否有记录
        $agent = KnscyRedpackAgent::where('redpack_no', $redPack_no)
            ->where('user_id', $this->user_id)->find();
        if (!empty($agent)) {
            $this->error('已经领取过了',[],1);
        }
        //是否領取完
        $total = KnscyRedpackAgent::where('redpack_no', $redPack_no)->count();
        if($total>= $info['total_num']){
            $this->error('领完了',[],1);
        }
        $data = [
            'redpack_no' => $redPack_no,
            'user_id' => $this->user_id,
            'redpack_type' => $info['redpack_type'],
            'agent_sn' => OrderService::agent_sn(),
            'discount' => $info['discount'],
            'end_time' => date('Y-m-d H:i:s', strtotime("+" . $info['limit_time'] . " days")),
        ];
        $agent = KnscyRedpackAgent::create($data);

        $this->success('success', $agent);
    }

    /**
     * 用户的获取可用的券
     * @return void
     */
    public function myCouponList()
    {
        $limit = $this->request->post('limit', 10);
        $page = $this->request->post('page', 1);
        $type = $this->request->post('type' );
        $status = $this->request->post('status', 0);
        //用户判断是否领取过

        $List = KnscyRedpackAgent::withoutGlobalScope(['uniacid'])
            ->alias('a')->where('a.status', 1)
            ->when($type>0, function ($query)use($type) {
                $query->where('a.redpack_type', $type);
            })
            //已用或 失效的 券
            ->when($status>-1, function ($query)use($status) {
                if($status==1){
                    $query->where('a.is_used', 1); //已用
                }else if($status==2){
                    //失效了的
                    $query->whereTime('a.end_time', '<', date('Y-m-d 23:59:59'));
                }else{
                    $query->where('a.is_used', 0); //可以用未过期
                    $query->whereTime('a.end_time', '>=', date('Y-m-d 23:59:59'));
                }
            })
            ->where('user_id', $this->user_id)
            ->join(KnscyRedpack::getTable()." p", "p.redpack_no= a.redpack_no")
            ->order(Db::raw('a.sort=0,a.sort asc,a.id desc'))
            ->field("a.*,p.title,p.subtitle,p.tag,p.describe")
            ->paginate(
                [
                    'list_rows' => $limit,
                    'page' => $page,
                ]
            )->each(function ($item)   {
                $item['start_date'] = date('Y-m-d', strtotime( $item['create_time']) );
                $item['end_date'] = date('Y-m-d',strtotime( $item['end_time']));
                $item['status_label'] = '可用';
                $item['can_used'] = 1;//表示可用
                if($item['is_used']==1){
                    $item['status_label'] = '已使用';
                    $item['can_used'] = 0;
                }else{
                    if(strtotime($item['end_time'])<time()){
                        $item['status_label'] = '已失效';
                        $item['can_used'] = 0;
                    }
                }

            });

        $this->success('success', $List);

    }

    /**
     * 我的优惠券详情页面
     *
     */
    public function myCouponDetail(){
        $agent_sn = $this->request->post('agent_sn');
        $info = KnscyRedpackAgent::withoutGlobalScope(['uniacid'])
            ->alias('a')
            ->join(KnscyRedpack::getTable()." p", "p.redpack_no= a.redpack_no")
            ->where('a.agent_sn', $agent_sn)
            ->where('a.redpack_type',2) //线下凭证才有效
            ->field("a.*,p.title,p.subtitle,p.tag,p.describe as content")
            ->where('a.user_id', $this->user_id)->find();
        if(!$info){
            $this->error('参数有误');
        }
        $info['qrcode_value'] = "verifyRedPack=".$info['agent_sn'];
        $this->success('success', $info);
    }
}